import { login, logout, getInfo } from "@/api/login";
import {   removeAgenyId } from "@/utils/auth";

const user = {
  state: {
    //token: getToken(),
    id: "",
    name: "",
    avatar: "",
    agencyId: '',
    roles: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AGENCYID: (state, agencyId) => {
      state.agencyId = agencyId;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            console.log(res);
            setToken(res.data.token);
            //commit("SET_TOKEN", res.data.token);
            commit("SET_AGENCYID", res.data.agencyId);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      //commit("SET_TOKEN", "");
      commit("agencyId", null);
      removeToken();
      location.href = "/index";

      // return new Promise((resolve, reject) => {
      //   logout(state.token).then(() => {
      //     commit('SET_TOKEN', '')
      //     commit('SET_ROLES', [])
      //     commit('SET_PERMISSIONS', [])
      //     removeToken()
      //     resolve()
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },
  },
};

export default user;
